<template>
  <div class="user-reg-layout  home-main-box">
    <div class="find-type-list">
      <div
        class="type-item"
        :class="type=='phone'?'type-item active webfont-Medium':'type-item webfont-Medium' "
        @click="changeFindType"
      >手机号找回</div>
      <div
        class="type-item"
        :class="type=='email'?'type-item active webfont-Medium':'type-item webfont-Medium' "
        @click="changeFindType"
      >邮箱找回</div>
    </div>
    <div class="user-reg-form form">

      <!-- 手机号找回开始 -->
      <template v-if="type=='phone'">
        <el-form ref="phoneForm" key="phoneForm1" :model="phoneFrom" :rules="phoneRules">

          <el-form-item key="phoneForm_user_phone" prop="user_phone" style="width: 100%;" maxlength="11">
            <el-input v-model.trim="phoneFrom.user_phone" type="text" placeholder="请输入您的电话" />
          </el-form-item>

          <div class="code-box">
            <el-form-item key="user_phone_SMS" prop="SMS">
              <el-input v-model.trim="phoneFrom.SMS" type="text" placeholder="短信验证码" maxlength="6" />
            </el-form-item>
            <el-form-item key="user_phone_SMS1" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">
              <el-input type="text" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">/>
              </el-input>
            </el-form-item>

            <el-button class="msg-btn" size="small" type="primary" @click="subPhoneEmailCode('phoneForm')">{{ codeText }}</el-button>

          </div>
          <el-form-item key="user_phone_pwd0" prop="pwd" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">
            <pwdInput placeholder="请输入您的密码" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;"></pwdInput>
          </el-form-item>
          <el-form-item key="user_phone_pwd" prop="pwd">
            <pwdInput v-model.trim="phoneFrom.pwd" placeholder="请输入您的密码"></pwdInput>
          </el-form-item>

          <el-form-item key="user_phone_pwd2" prop="pwd2">

            <pwdInput v-model.trim="phoneFrom.pwd2" placeholder="请再次输入您的密码" @keyup.native.enter="submitFindPwd('phoneForm')"></pwdInput>
          </el-form-item>

          <div class="find-btn-list">
            <el-button type="success" size="small" @click="submitFindPwd('phoneForm')">完成</el-button>
            <span @click="goLogin">使用已有账户登录</span>
          </div>

        </el-form>
      </template>
      <!-- 手机号注册结束 -->

      <!-- 邮箱注册开始 -->
      <template v-if="type=='email'">
        <el-form ref="emailForm" key="emailForm" :model="emailFrom" :rules="emailRules">

          <el-form-item key="emailForm_user_email" prop="user_email" style="width: 100%;">
            <el-input v-model.trim="emailFrom.user_email" type="text" placeholder="请输入您的邮箱" />
          </el-form-item>

          <div class="code-box">
            <el-form-item key="emailForm_code" prop="code">
              <el-input v-model.trim="emailFrom.code" placeholder="邮箱验证码" maxlength="6" />
            </el-form-item>
            <el-form-item key="emailForm_code1" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">
              <el-input placeholder="邮箱验证码" maxlength="6" />
            </el-form-item>

            <el-button class="msg-btn" size="small" type="primary" @click="subPhoneEmailCode('emailForm')">{{ codeText }}</el-button>

          </div>

          <el-form-item key="emailForm_pwd0" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">
            <pwdInput style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;" />
          </el-form-item>
          <el-form-item key="emailForm_pwd" prop="pwd">
            <pwdInput v-model.trim="emailFrom.pwd" show-password placeholder="请输入您的密码"></pwdInput>
          </el-form-item>

          <el-form-item key="emailForm_pwd2" prop="pwd2">

            <pwdInput v-model.trim="emailFrom.pwd2" show-password placeholder="请再次输入您的密码" @keyup.native.enter="submitFindPwd('emailForm')"></pwdInput>
          </el-form-item>

          <div class="find-btn-list">
            <el-button type="success" size="small" @click="submitFindPwd('emailForm')">完成</el-button>
            <span @click="goLogin">使用已有账户登录</span>
          </div>

        </el-form>
      </template>
      <!-- 邮箱注册结束 -->
    </div>
  </div>
</template>
<script>
import {
  userCode, // 验证图片验证码是否正确；
  createCode,
  emailRegister, // 邮箱验证码获取
  smsRegister, // 手机验证码获取
  retrievePwd
} from '@/api/user.js'
  // type: 'register' // 注册字段
  // type: 'retrieve' ,// 找回字段
  // type:'modifyEmail'//更换字段
import {
  isValidPhone,
  isValidEmail,
  isValidCode
} from '@/utils/validate'

let codeTime // 定时器
export default {
  data() {
    // 手机密码一致验证
    var validatePhonePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.phoneFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 邮箱密码一致验证
    var validateMailPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.emailFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      type: 'phone',
      code: undefined, // 验证码图片路径
      codeText: '获取验证码', // 验证码按钮文字
      countDown: 0, // 倒计时秒数
      agreeWith: false,
      phoneFrom: {
        user_phone: '',
        SMS: '',
        pwd: '',
        pwd2: ''
      },
      phoneRules: {
        user_phone: [{
          required: true,
          message: '请输入您的手机号码',
          trigger: 'blur'
        },
        {
          validator: isValidPhone,
          trigger: 'blur'
        }
        ],
        SMS: [{
          required: true,
          message: '请输入您的验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        pwd2: [{
          required: true,
          validator: validatePhonePass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ]
      },
      emailFrom: {
        user_email: '',
        pwd: '',
        code: '',
        pwd2: ''
      },
      emailRules: {
        user_email: [{
          required: true,
          message: '请输入您的邮箱',
          trigger: 'blur'
        },
        {
          validator: isValidEmail,
          trigger: 'blur'
        }
        ],
        code: [{
          required: true,
          message: '请输入邮箱验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        pwd2: [{
          required: true,
          validator: validateMailPass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ]
      }
    }
  },
  mounted() {
    // this.createCode()
  },
  methods: {
    // 获取验图片证码
    // async createCode() {
    //   const res = await createCode()
    //   const blob = new Blob([res.data], {
    //     type: 'image/png'
    //   })
    //   const url = window.URL.createObjectURL(blob)
    //   this.code = url
    // },

    // 发送手机或者邮箱验证码
    subPhoneEmailCode(type) {
      if (this.countDown > 0) return false

      if (type === 'phoneForm') {
        // 如果是请求发送手机验证码
        var MobileRegex = /^1[0-9]{10}$/
        const value = this.phoneFrom.user_phone
        if (!MobileRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的手机号码!')
        } else {
          this.getPhoneCode()
        }
        // 手机验证结束
      } else {
        // 如果是邮箱
        var mailRegex = /^\w*@[-a-zA-Z0-9]{1,20}\.[0-9a-z]{2,3}$/
        const value = this.emailFrom.user_email
        if (!mailRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的邮箱!')
        } else {
          this.getEmailCode()
        }
      }
    },

    // 邮箱验证码获取
    async getEmailCode() {
      const obj = {
        account: this.emailFrom.user_email,
        type: 'retrieve' // 找回字段
      }
      const {
        data
      } = await emailRegister(obj)

      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },
    // 手机验证码获取
    async getPhoneCode() {
      const obj = {
        account: this.phoneFrom.user_phone,
        type: 'retrieve' // 找回字段
      }
      const {
        data
      } = await smsRegister({ ...obj
      })
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },

    // 验证码倒计时
    runTime() {
      const that = this
      this.countDown = 60
      codeTime = setInterval(() => {
        if (that.countDown <= 1) {
          clearInterval(codeTime)
          that.countDown = 0
          this.codeText = '获取验证码'
        } else {
          that.countDown -= 1
          this.codeText = this.countDown + 's'
        }
      }, 1000)
    },

    // 提交找回密码
    submitFindPwd(form) {
      this.$refs[form].validate(async(valid) => {
        if (valid) {
          let data = {}
          if (form.indexOf('phone') !== -1) {
            data = {
              mobile: this.phoneFrom.user_phone,
              pwd: this.phoneFrom.pwd,
              code: this.phoneFrom.SMS
            }
          } else {
            data = {
              email: this.emailFrom.user_email,
              pwd: this.emailFrom.pwd,
              code: this.emailFrom.code
            }
          }
          const res = await retrievePwd({ ...data
          })
          if (res.data.code !== 20000) {
            // 证明注册失败了
            this.$message.closeAll()
            this.$message.error(res.data.message || '注册失败，请稍后重试')
          } else {
            this.$message.closeAll()
            this.$message({
              message: res.data.message || '密码更改成功，即将跳转登录',
              type: 'success'
            })
            this.goLogin()
          }
        } else {
          console.log('表单验证失败')
        }
      })
    },

    // 改变找回密码形式
    changeFindType() {
      // 清除定时器
      if (codeTime) {
        clearInterval(codeTime)
      }
      // 重置获取验证码按钮字段
      this.countDown = 0
      this.codeText = '获取验证码'
      // 同意协议重置
      this.agreeWith = false
      if (this.type === 'phone') {
        this.$refs['phoneForm'].resetFields()
        this.$nextTick(function() {
          this.type = 'email'
        })
      } else {
        this.$refs['emailForm'].resetFields()
        this.$nextTick(function() {
          this.type = 'phone'
        })
      }
    },
    // 去登录页面
    goLogin() {
      if (this.type == 'phone') {
        this.$refs['phoneForm'].resetFields()
      } else {
        this.$refs['emailForm'].resetFields()
      }
      this.$nextTick(function() {
        this.$emit('changeType', 'login')
      })
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import './style/form.scss';

  .type-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20px;

    .blue-btn {
      width: 48%;
    }
  }
</style>
